<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
import type { IAttrItem, ISkuItem, IValueItem } from '@/stores/types';
import { useAttrsStore } from '@/stores/attrs';
import { getSkuList } from '@/utils';
import { useSkusStore } from '@/stores/skus';
import { ElMessage } from 'element-plus';

interface IAttrFormItem extends IAttrItem {
  selecteds?: string[];
}

const isEdit = ref(true)
// 默认属性
const attrsData = ref<IAttrFormItem[]>([])
const { attrList = [] } = useAttrsStore()
attrsData.value = attrList.map((item) => {
  return {
    ...item,
    selecteds: item.attrValues.map(v => v.valueId),
  }
})

// 选中的属性
const selectedAttrData = ref<IAttrFormItem[]>([])
// 选好属性后创建 组合
const skuData = ref<ISkuItem[]>([])

const handleCreateAttrs = () => {
  // 保存选中的属性
  const _selectedAttrData = attrsData.value.reduce((target, current) => {
    const { selecteds, attrValues } = current
    if (selecteds!.length === 0) {
      return target;
    }
    // 选中的属性值
    const values = attrValues.filter(v => selecteds!.includes(v.valueId))
    const { attrId, attrLabel } = current
    const targetItem = {
      attrId,
      attrLabel,
      attrValues: [...values]
    }
    target.push(targetItem)
    return target
  }, [] as IAttrFormItem[])

  console.log('_selectedAttrData--', _selectedAttrData)
  selectedAttrData.value = _selectedAttrData

  // 保存选中的属性值
  const selectedAttrValues = _selectedAttrData.reduce((target, current) => {
    const { attrValues } = current
    // 保留当前属性信息 和 属性值 信息
    const targetItem = attrValues.map((v) => {
      const { attrId, attrLabel } = current
      return {
        ...v,
        attrId,
        attrLabel,
      }
    })
    target.push(targetItem)
    return target
  }, [] as IValueItem[][])
  console.log('selectedAttrValues--', selectedAttrValues)
  // 组合成 sku 的信息
  const _skuData = getSkuList(selectedAttrValues)
  // 拼装价格、库存
  skuData.value = _skuData.map((item) => {
    return {
      skuAttrs: item,
      price: 1,
      stock: 1
    }
  })
  console.log('skuData--', skuData.value)
  isEdit.value = false
}
// 表头
const selectedAttrLabels = computed(() => skuData.value?.[0]?.skuAttrs?.map(v => {
  return {
    attrId: v.attrId,
    attrLabel: v.attrLabel,
  }
}))

// 填充 默认1
const handleFill = (key: 'stock' | 'price', value: number) => {
  skuData.value.forEach((item) => {
    item[key] = value === 0 ? 1 : value
  })
}
// 移除
const handleRemove = (index: number) => {
  skuData.value.splice(index, 1)
}

// sku 入库
const { stockIn, createSkuAttrs } = useSkusStore()

// 确认 sku， 则入库
const handleCreateSku = () => {
  console.log('create skuData--', skuData.value)
  // sku 入库
  stockIn(skuData.value)
  // 选中的属性表也保存一下
  createSkuAttrs(selectedAttrData.value)
  ElMessage.success('操作成功')
}

// 初始化
const init = () => {
  handleCreateAttrs()
  handleCreateSku()
}
onMounted(init)
</script>

<template>
  <main>
    <el-card>
      <el-form
        :model="{ attrsData }"
        label-position="left"
        label-suffix="："
        :disabled="!isEdit"
        inline
      >
        <template
          v-for="item of attrsData"
          :key="item.attrId"
        >
          <el-form-item :label="item.attrLabel">
            <el-select
              v-model="item.selecteds"
              multiple
              filterable
              default-first-option
              :reserve-keyword="false"
              placeholder="create new attr"
            >
              <el-option
                v-for="(it, idx) of item.attrValues"
                :key="idx"
                :label="it.valueLabel"
                :value="it.valueId"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-form>
      <el-row type="flex" justify="end">
        <el-button
          type="primary"
          :disabled="isEdit"
          @click="isEdit = true"
        >编辑</el-button>
        <el-button
          type="success"
          :disabled="!isEdit"
          @click="handleCreateAttrs"
        >确定</el-button>
      </el-row>
    </el-card>
    <el-card class="mt-2">
      <el-table :data="skuData" border>
        <el-table-column label="序号" align="center" type="index"></el-table-column>
        <template v-for="(item, index) of selectedAttrLabels" :key="item.attrId">
          <el-table-column
            :label="item.attrLabel"
            align="center"
          >
            <template #default="{ row }">{{ row.skuAttrs[index].valueLabel }}</template>
          </el-table-column>
        </template>
        <el-table-column label="价格" align="center">
          <template #default="{ row, $index }">
            <el-input
              v-model.number="row.price"
            >
              <template v-if="$index === 0" #append>
                <el-button text @click="handleFill('price', row.price)">填充</el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="库存" align="center">
          <template #default="{ row, $index }">
            <el-input
              v-model.number="row.stock"
            >
              <template v-if="$index === 0" #append>
                <el-button text @click="handleFill('stock', row.stock)">填充</el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ $index }">
            <el-button
              type="danger"
              size="small"
              @click="handleRemove($index)"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" class="mt-2">
        <el-button
          type="success"
          :disabled="skuData.length === 0"
          @click="handleCreateSku"
        >入库</el-button>
      </el-row>
    </el-card>
  </main>
</template>
